import { login, getMenu } from '@/api/user'
import {
  getToken, setToken, removeToken,
  getUserInfo, setUserInfo,
  getMenuList, setMenuList
} from '@/utils/auth'
import router, { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
    menuList: getMenuList()
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, info) => {
    state.userInfo = info
    state.userId = info.id
  },
  SET_MENU_LIST: (state, menuList) => {
    state.menuList = menuList
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(res => {
        const response = res.data
        commit('SET_TOKEN', response.token)
        commit('SET_INFO', response)
        setToken(response.token)
        setUserInfo(response)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getMenu({ commit }) {
    return new Promise((resolve, reject) => {
      getMenu().then(response => {
        commit('SET_MENU_LIST', response.data.adminMenus)
        setMenuList(response.data.adminMenus)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
      router.replace({
        path: '/login'
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

